﻿using Com.Lancetinc.Evs.Cameras;
using Com.Lancetinc.Evs.Models;
using System;
using System.Linq;
using Telerik.Windows.Controls;
using Telerik.Windows.MediaFoundation;

namespace Com.Lancetinc.Evs.Helpers
{
    public class RadWebCamHelper
    {
        /// <summary>
        /// 判断摄像头是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool IsCameraExists(string name)
        {
            return RadWebCam.GetVideoCaptureDevices().Any(x => x.FriendlyName == name);
        }

        public static MediaFoundationVideoFormatInfo GetVideoFormat(MediaFoundationDeviceInfo videoDevice, VideoDeviceInfo info)
        {
            var videoFormats = RadWebCam.GetVideoFormats(videoDevice);
            var filteredFormats = videoFormats.Where(x => x.SubTypeDisplayName == info.VideoFormat).ToList();

            var videoFormat = filteredFormats.FirstOrDefault(x => x.FrameSizeWidth == info.VideoWidth && x.FrameSizeHeight == info.VideoHeight);
            if (videoFormat != null)
            {
                return videoFormat;
            }

            var detas = filteredFormats.Select(x => Math.Pow(x.FrameSizeWidth - info.VideoWidth, 2) + Math.Pow(x.FrameSizeHeight - info.VideoHeight, 2)).ToArray();
            int indexForMin = 0;
            for (int i = 1; i < detas.Length; i++)
            {
                if (detas[i] < detas[indexForMin])
                {
                    indexForMin = i;
                }
            }

            return filteredFormats[indexForMin];
        }

        public static bool LoadWhiteBalance(string videoDeviceName)
        {
            var videoDevices = RadWebCam.GetVideoCaptureDevices().AsQueryable().ToArray();
            for (int i = 0; i < videoDevices.Length; i++)
            {
                if (videoDevices[i].FriendlyName == videoDeviceName)
                {
                    WhiteBalanceHelper.WriteSettingToDevice(i);
                    return true;
                }
            }
            return false;
        }
    }
}
